package com.chart.web.controller.chart;

import com.chart.common.core.domain.AjaxResult;
import com.chart.web.controller.ContentParamVo;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * openai
 *
 * @author 罗继全
 * 2024/7/17 15:20
 */

@RestController
@RequestMapping("/gpt")
public class AiController {

    /**
     * ai 问图
     * @param paramVo
     * @return
     */
    @PostMapping(value = "/chart")
    public AjaxResult questionV2(@RequestBody ContentParamVo paramVo) {
        System.out.println(paramVo.getContent());
        Integer number = paramVo.getNumber(); // 获取number参数
        // 如果number参数为null，默认为1
        if (number == null) {
            number = 1;
        }
        if (number == 1) {
            return callExternalApi(paramVo.getContent());
        } else {
            List<String> resultList = new ArrayList<>();
            for (int i = 0; i < number; i++) {
                resultList.add(callExternalApi(paramVo.getContent()).get("data").toString());
            }
            return AjaxResult.success("操作成功", resultList);
        }
    }

    private AjaxResult callExternalApi(String content) {
        String apiKey = "sk-GZGjN52ugqe4viXGAcF91dF137Ec41408dC5650b9a4dB7F4";
        String apiUrl = "https://aihubmix.com/v1/chat/completions";

        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(apiUrl);

        // 设置请求头
        httpPost.setHeader("Authorization", "Bearer " + apiKey);
        httpPost.setHeader("Content-Type", "application/json");
        String requestBody = "{" +
                "\"model\": \"gpt-4o-2024-08-06\"," +
                "\"messages\": [{" +
                "\"role\": \"user\"," +
                "\"content\": \"" + content + "\"" +
                "}]" +
                "}";

        String responseString;
        String generatedText;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            httpPost.setEntity(new StringEntity(requestBody));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity);
            JsonNode jsonResponse = objectMapper.readTree(responseString);
            generatedText = jsonResponse.path("choices").get(0).path("message").path("content").asText();

            System.out.println(generatedText);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("调用外部接口失败");
        }

        return AjaxResult.success("操作成功", generatedText);
    }


/*    @PostMapping(value = "/chart")
    public AjaxResult questionV2(@RequestBody ContentParamVo paramVo) {
        System.out.println(paramVo.getContent());
        int number = paramVo.getNumber(); // 获取number参数

        if (number == 1) {
            return callExternalApi(paramVo.getContent());
        } else {
            List<String> resultList = new ArrayList<>();
            for (int i = 0; i < number; i++) {
                resultList.add("Result " + (i + 1));
            }
            return AjaxResult.success("操作成功", resultList);
        }
    }

    private AjaxResult callExternalApi(String content) {
        String apiKey = "sk-GZGjN52ugqe4viXGAcF91dF137Ec41408dC5650b9a4dB7F4";
        String apiUrl = "https://aihubmix.com/v1/chat/completions";

        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(apiUrl);

        // 设置请求头
        httpPost.setHeader("Authorization", "Bearer " + apiKey);
        httpPost.setHeader("Content-Type", "application/json");

        String requestBody = "{" +
                "\"model\": \"gpt-4o-2024-05-13\"," +
                "\"messages\": [{" +
                "\"role\": \"user\"," +
                "\"content\": \"" + content + "\"" +
                "}]" +
                "}";

        String responseString;
        String generatedText;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            httpPost.setEntity(new StringEntity(requestBody));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity);
            JsonNode jsonResponse = objectMapper.readTree(responseString);
            generatedText = jsonResponse.path("choices").get(0).path("message").path("content").asText();

            System.out.println(generatedText);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("调用外部接口失败");
        }

        return AjaxResult.success("操作成功", generatedText);
    }*/

    @PostMapping(value = "/chartPhoto")
    public AjaxResult questionV20(ContentParamVo paramVo, @RequestPart(value = "file", required = false) MultipartFile file) {
        System.out.println(paramVo.getContent());

        String apiKey = "sk-GZGjN52ugqe4viXGAcF91dF137Ec41408dC5650b9a4dB7F4";
        String apiUrl = "https://aihubmix.com/v1/chat/completions";
//        String apiUrl = "https://api.xiaoai.plus/v1/chat/completions";

        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(apiUrl);

        // 设置请求头
        httpPost.setHeader("Authorization", "Bearer " + apiKey);
        httpPost.setHeader("Content-Type", "application/json");
        System.out.println(paramVo.getContent());
        String value = "Hello, ChatGPT!";
        // 构建请求体
        String requestBody = "{" +
                "\"model\": \"gpt-4o\"," +
                "\"messages\": [{" +
                "\"role\": \"user\"," +
                "\"content\": \"" + paramVo.getContent() + "\"" +
                "}]" +
                "}";

        System.out.println(requestBody);
        String responseString = null;
        String generatedText = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            httpPost.setEntity(new StringEntity(requestBody));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity);
            JsonNode jsonResponse = objectMapper.readTree(responseString);
            generatedText = jsonResponse.path("choices").get(0).path("message").path("content").asText();
            System.out.println(generatedText);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success("操作成功", generatedText);
    }


    @PostMapping(value = "/chartPhoto/ai")
    public AjaxResult questionV200(ContentParamVo paramVo, @RequestPart(value = "file", required = false) MultipartFile file) {
        System.out.println(paramVo.getContent());

        String apiKey = "sk-GZGjN52ugqe4viXGAcF91dF137Ec41408dC5650b9a4dB7F4";
        String apiUrl = "https://aihubmix.com/v1/images/generations";

        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(apiUrl);

        // 设置请求头
        httpPost.setHeader("Authorization", "Bearer " + apiKey);
        httpPost.setHeader("Content-Type", "application/json");
        System.out.println(paramVo.getContent());
        String value = "Hello, ChatGPT!";
        // 构建请求体
        String requestBody = "{" +
                "\"model\": \"gpt-4o\"," +
                "\"messages\": [{" +
                "\"role\": \"user\"," +
                "\"content\": \"" + paramVo.getContent() + "\"" +
                "}]" +
                "}";
        String responseString = null;
        String generatedText = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            httpPost.setEntity(new StringEntity(requestBody));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity);
            JsonNode jsonResponse = objectMapper.readTree(responseString);
            generatedText = jsonResponse.path("choices").get(0).path("message").path("content").asText();
            System.out.println(generatedText);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success("操作成功", generatedText);
    }


}

